<template>
  <div class="setting">
    <el-card>
      <el-tabs>
        <el-tab-pane label="角色管理">
          <el-button
            type="primary"
            style="margin-bottom: 20px"
            @click="add"
          >新增角色</el-button>
          <el-table :data="list" border>
            <el-table-column label="序号" type="index" width="80px" />
            <el-table-column prop="name" label="角色" />
            <el-table-column prop="description" label="描述" />
            <el-table-column label="操作">
              <template v-slot="{ row }">
                <div>
                  <el-button type="success">分配权限</el-button>
                  <el-button type="primary" @click="edit(row)">编辑</el-button>
                  <el-button type="danger" @click="del(row.id)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="paging">
            <el-pagination
              :current-page.sync="page.page"
              :page-sizes="[1, 2, 5, 10]"
              :page-size.sync="page.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="getData"
              @current-change="getData"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane lazy label="公司信息"><Info /></el-tab-pane>
      </el-tabs>
      <Add ref="add" @getData="getData" />
    </el-card>
  </div>
</template>
<script>
import { sysRole, sysRoleDelete } from '@/api/setting'
import Add from './components/add.vue'
export default {
  components: {
    Add,
    Info: () => import('./components/info.vue')
  },
  data() {
    return {
      list: [{}],
      page: {
        page: 1,
        pagesize: 10
      },
      total: 50
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const { data: res } = await sysRole(this.page)
      this.list = res.rows
      this.total = res.total
    },
    // 新增
    add() {
      this.$refs.add.isShow = true
      this.$refs.add.mode = 'add'
    },
    // 删除角色点击
    del(id) {
      this.$confirm('您确定删除该角色吗？', '温馨提示')
        .then(async() => {
          // 调用删除api
          await sysRoleDelete(id)
          // 提示
          this.$message.success('删除成功')
          // 刷新列表数据
          // 如果删除的数据页码>1 且当前页只有一条数据时，页码要往前一页
          if (this.page.page > 1 && this.list.length <= 1) {
            this.page.page--
          }
          this.getData()
        })
        .catch(() => {})
    },
    // 编辑
    edit(row) {
      console.log(row)
      this.$refs.add.isShow = true
      this.$refs.add.mode = 'edit'
      this.$refs.add.form = { ...row }
    }
  }
}
</script>
<style lang="scss" scoped>
.setting {
  padding: 20px;
}
.paging {
  margin: 20px auto;
  text-align: center;
}
</style>
